package jalus.blog;

import jalus.Action;
import jalus.model.FileIndex;
import jalus.pojo.Pageindicator;
import jalus.service.ConfigureService;
import jalus.service.FileService;
import jalus.service.PostService;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.math.NumberUtils;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class FileManagerServlet extends Action {
	
	/**
	 * 显示文件/删除文件
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			error();
			return;
		}
		User user = userService.getCurrentUser();
		
		FileService fileService = FileService.getInstance();
		String action = req.getParameter("action");
		if(action!=null && action.equalsIgnoreCase("delete")){
			/* 删除文件 */
			Long id = new Long(req.getParameter("id"));
			fileService.deleteFile(id);
			resp.sendRedirect(req.getHeader("Referer"));
			return;
		}
		
		int totalFileNum = fileService.getFileNum();
		int pageNum = NumberUtils.toInt(req.getParameter("pagenum"), 1);
		int fileNumPerPage = ConfigureService.getInstance().getFileNumPerPage();
		Pageindicator pageindicator = new Pageindicator(totalFileNum, pageNum, fileNumPerPage);
		
		List<FileIndex> fileList = fileService.getFileIndexListByRange(pageindicator.getCurrentStartIndex(), 
				pageindicator.getCurrentEndIndex());
		
		Map root = new HashMap();
		root.put("userService", userService);
		root.put("user", user);
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		root.put("focustab", "file");
		root.put("uri", req.getRequestURI());
		
		root.put("page", pageindicator);
		root.put("page_base", "/file?page=");
		root.put("filelist", fileList);
		
		processTemplate(root, "filemanager.html", resp);
	}
	
	/**
	 * 上传文件
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		if(!userService.isUserLoggedIn() || !userService.isUserAdmin()){
			error();
			return;
		}
		
		String CKEditorFuncNum = req.getParameter("CKEditorFuncNum");
		// ckeditor 文件上传
		if(CKEditorFuncNum != null){
			String type = req.getParameter("Type");
			if(type == null){
				type = "File";
			}
			ServletFileUpload fileUpload = new ServletFileUpload();
			/* 最大1MB */
			fileUpload.setSizeMax(1024000);
			FileItemIterator iter;
			String fileUrl = null;
			try {
				iter = fileUpload.getItemIterator(req);
				while (iter.hasNext()) {
					FileItemStream item = iter.next();
					if (!item.isFormField()	&& item.getFieldName().equals("upload")) {
						InputStream in = item.openStream();
						byte[] fileData = new byte[1024000];
						int offset = 0;
						int length = -1;
						while((length = in.read(fileData, offset, 1024000)) >=0){
							offset += length;
						}
						in.close();
						fileData = Arrays.copyOfRange(fileData, 0, offset);
						Blob blob = new Blob(fileData);
						jalus.model.File file = new jalus.model.File(item.getName(), item.getContentType(),
								blob, new Date());
						long fileid = FileService.getInstance().add(file);
						fileUrl = "/showfile/" + fileid;
					}
				}
				if(fileUrl != null){
					resp.setContentType("text/html; charset=UTF-8");  
					resp.setHeader("Cache-Control", "no-cache");  
					PrintWriter out = resp.getWriter();
					String result = "<script type=\"text/javascript\">"
						+ "window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" + fileUrl + "','')"
						+ "</script>";
					out.print(result);
					out.flush();
					out.close();
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			return;
		}
		
		ServletFileUpload fileUpload = new ServletFileUpload();
		/* 最大1MB */
		fileUpload.setSizeMax(1024000);
		FileItemIterator iter;
		try {
			iter = fileUpload.getItemIterator(req);
			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				if (!item.isFormField()	&& item.getFieldName().equals("uploadfile")) {
					InputStream in = item.openStream();
					byte[] fileData = new byte[1024000];
					int offset = 0;
					int length = -1;
					while((length = in.read(fileData, offset, 1024000)) >=0){
						offset += length;
					}
					in.close();
					fileData = Arrays.copyOfRange(fileData, 0, offset);
					Blob blob = new Blob(fileData);
					jalus.model.File file = new jalus.model.File(item.getName(), item.getContentType(), 
							blob, new Date());
					FileService.getInstance().add(file);
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		resp.sendRedirect("/file");
		
	}
}
